package com.ruoyi.api.worker;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SmsTemplete;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.JiajiaWorker;
import com.ruoyi.system.domain.JiajiaWorkerPhoto;
import com.ruoyi.system.service.IJiajiaUserService;
import com.ruoyi.system.service.IJiajiaWorkerPhotoService;
import com.ruoyi.system.service.IJiajiaWorkerService;
import com.ruoyi.system.utils.SendSms;
import com.ruoyi.system.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/worker")
@Api(tags = "社工端登录接口")
public class ApiWorkerController {

    @Autowired
    private IJiajiaWorkerService workerService;
    @Autowired
    private IJiajiaWorkerPhotoService photoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IJiajiaUserService userService;

    @ApiOperation("登陆")
    @PostMapping("/login")
    public AjaxResult login(@RequestParam String phone,
                            @RequestParam String code)
    {

            if (StringUtils.isEmpty(phone)){
                return AjaxResult.error("请输入手机号");
            }

            if (StringUtils.isEmpty(code)){
                return AjaxResult.error("请先获取验证码");
            }
            
            String realCode =  redisTemplate.opsForValue().get(TokenUtil.jiajia_worker_phone_login_code +phone);
            if (StringUtils.isEmpty(realCode)){
                return AjaxResult.error("请先获取验证码");
            }
            if (!realCode.equals(code)){
                return AjaxResult.error("验证码不对");
            }
        JiajiaWorker worker = new JiajiaWorker();
        worker.setPhone(phone);
        List<JiajiaWorker> workerList =  workerService.selectWorkerList(worker);
        if (workerList.isEmpty()){
            //return AjaxResult.error("还未注册账号，请联系管理员");
            //直接注册到数据库
            worker.setArtAvatar("https://www.baijixing.com.cn/profile/upload/2025/02/26/d02ffff5-9421-45b1-a1e4-699f804feec1.png");
            worker.setName(phone);
            worker.setStatus(1);
            worker.setDel(0);
            workerService.insert(worker);
        }else{
            worker = workerList.get(0);
        }

        if(worker == null){
            return AjaxResult.error("还未注册账号，请联系管理员");
        }
        if (worker.getStatus().intValue() == 2)return AjaxResult.error("此账户已被禁用!");
        if (worker.getDel().intValue() == 1)return AjaxResult.error("此账户已注销!");
        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(TokenUtil.jiajia_reids_token+uuid, worker.getId()+"",60, TimeUnit.DAYS);
        return AjaxResult.success(uuid);
    }

    @ApiOperation("我的相册")
    @PostMapping("/myPhotos")
    public AjaxResult myPhotos()
    {
        JiajiaWorkerPhoto jiajiaWorkerPhoto = new JiajiaWorkerPhoto();
        jiajiaWorkerPhoto.setWid(TokenUtil.getUid());
        PageHelper.orderBy("addtime desc");
        List<JiajiaWorkerPhoto> workerPhotos =  photoService.selectJiajiaWorkerPhotoList(jiajiaWorkerPhoto);
        return AjaxResult.success(workerPhotos);
    }

    @ApiOperation("上传相册")
    @PostMapping("/uploadPhoto")
    public AjaxResult uploadPhoto(@RequestParam String photo)
    {
        JiajiaWorkerPhoto jiajiaWorkerPhoto = new JiajiaWorkerPhoto();
        jiajiaWorkerPhoto.setWid(TokenUtil.getUid());
        jiajiaWorkerPhoto.setType(1L);
        jiajiaWorkerPhoto.setUrl(photo);
        jiajiaWorkerPhoto.setSort(100L);
        photoService.insertJiajiaWorkerPhoto(jiajiaWorkerPhoto);
        return AjaxResult.success("上传成功");
    }

    @ApiOperation("删除相册")
    @PostMapping("/delPhoto")
    public AjaxResult delPhoto(@RequestParam Long id)
    {
        JiajiaWorkerPhoto photo = photoService.selectJiajiaWorkerPhotoById(id);
        if (photo == null){
            return AjaxResult.error("删除失败");
        }
        photoService.deleteJiajiaWorkerPhotoById(id);

        return AjaxResult.success("删除成功");
    }

    @ApiOperation("设为主页照片")
    @PostMapping("/setArtPhoto")
    public AjaxResult setArtPhoto(@RequestParam @ApiParam(value = "相册照片id") Long id)
    {
        JiajiaWorker worker=workerService.selectJiajiaWorkerById(TokenUtil.getUid());
        if (worker ==null)return AjaxResult.notLogin();

        JiajiaWorkerPhoto photo = photoService.selectJiajiaWorkerPhotoById(id);
        if (photo == null){
            return AjaxResult.error("设置为主页照片失败");
        }

        worker.setArtAvatar(photo.getUrl());
        workerService.updateJiajiaWorker(worker);

        return AjaxResult.success();
    }

    @ApiOperation("获取短信验证码")
    @PostMapping("getLoginCode")
    public AjaxResult getLoginCode(@RequestParam String phone, @RequestParam(required = false) String scene){

        try {
            JiajiaWorker worker = new JiajiaWorker();
            worker.setPhone(phone);
            List<JiajiaWorker> userList =  workerService.selectWorkerList(worker);
            if (userList.isEmpty()){
                worker.setName(phone);
                worker.setArtAvatar("https://www.baijixing.com.cn/profile/upload/2025/02/26/d02ffff5-9421-45b1-a1e4-699f804feec1.png");
                workerService.insert(worker);
            }

            String code = ""+(int)((Math.random()*9+1)*1000);

            //开始发送短信
            SendSmsResponse response = SendSms.sendSms(phone,code, SmsTemplete.TP_LOGIN_CODE);
            if (response.getCode().equals("OK")){
                //存redis
                if(StrUtil.equals("register", scene)){//注册
                    redisTemplate.opsForValue().set( TokenUtil.jiajia_worker_phone_register_code + phone,code,SmsTemplete.CODE_EXPIRED, TimeUnit.MINUTES);
                }else{//登录
                    redisTemplate.opsForValue().set( TokenUtil.jiajia_worker_phone_login_code + phone,code,SmsTemplete.CODE_EXPIRED, TimeUnit.MINUTES);
                }
                return AjaxResult.success("短信发送成功");
            }else{
                return AjaxResult.error("发送失败"+response.getMessage());
            }

        }catch (Exception e){
            System.out.println(e.toString());
            return AjaxResult.error("发送异常"+e.toString());
        }

    }

    @ApiOperation("技师注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestParam String name,
                                @RequestParam String phone,
                               @RequestParam String code){
        if(StrUtil.isEmpty(name)){
            return AjaxResult.error("技师名称不能为空");
        }
        if(StrUtil.isEmpty(phone)){
            return AjaxResult.error("技师手机号不能为空");
        }

            String realCode =  redisTemplate.opsForValue().get(TokenUtil.jiajia_worker_phone_register_code +phone);
            if (StringUtils.isEmpty(realCode)){
                return AjaxResult.error("请先获取验证码");
            }
            if (!realCode.equals(code)){
                return AjaxResult.error("验证码错误，请重试");
            }


        if(registerWorker(phone, name) != null){
            return AjaxResult.success(name+"注册成功，等待平台审核");
        }
        return AjaxResult.error(name+"注册失败，请重试");
    }

    private JiajiaWorker registerWorker(String phone, String name){
        JiajiaWorker jiajiaWorker = new JiajiaWorker();
        jiajiaWorker.setPhone(phone);
        jiajiaWorker.setName(name);
        jiajiaWorker.setStatus(3);
        jiajiaWorker.setMoney(BigDecimal.ZERO);

        int resCount = workerService.insertJiajiaWorker(jiajiaWorker);
        if(resCount > 0){
            return jiajiaWorker;
        }
        return null;
    }

    @ApiOperation("注销账户")
    @PostMapping("/zhuXiao")
    public AjaxResult zhuXiao(){

//        JiajiaWorker worker = workerService.selectJiajiaWorkerById(TokenUtil.getUid());
//        worker.setDel(1);
//        workerService.updateJiajiaWorker(worker);
        return AjaxResult.success("此功能暂时已关闭");
    }

}
